import os
from win32com.client import Dispatch

class DmBase():
    """大漠封装类"""
    def __init__(self,_hwnd=0,dm_path=''):
        self.setHwnd(_hwnd)
        self.path = dm_path
        self.dm = self.createDm()
        self.setShowError()
        self.setFont()
        self.getChikaHwnd()
        ###self.getYeSeHwnd()
        self.getConfigHwnd()
        self.bindWindow(self.dm,self.hwnd)
    
    def createDm(self):
        """ 获取并初始化大漠插件
            需要管理员权限运行
        """
        try:
            _dm = Dispatch('dm.dmsoft')
            return _dm
        except Exception:
            _path = self.path + '\\Code\\'
            os.system(r'regsvr32 /s %s\dm.dll' % _path)
            try:
                _dm = Dispatch('dm.dmsoft')
                return _dm
            except Exception:
                print("错误：需要管理员权限运行！！!")
        return None
    
    def setHwnd(self,_hwnd):
        """设置句柄"""
        if _hwnd == '':
            self.hwnd = 0
            return None
        self.hwnd = int(_hwnd)
        return None
    
    def getChikaHwnd(self):
        """查找Chika登录器的句柄"""
        if self.dm != None:
            _dm = self.dm
            hwnd = _dm.FindWindowEx(0,"WTWindow","")
            hwnd = _dm.FindWindowEx(hwnd,"Afx:400000:b:10003:900010:0","")
            hwnd = _dm.FindWindowEx(hwnd,"Shell Embedding","")
            hwnd = _dm.FindWindowEx(hwnd,"Shell DocObject View","")
            hwnd = _dm.FindWindowEx(hwnd,"Internet Explorer_Server","")
            if hwnd == 0:
                return self.hwnd
            print("已找到程序：" + str(hwnd))
            self.setHwnd(hwnd)
        return self.hwnd
    
    def getYeSeHwnd(self):
        """查找夜色登录器的句柄"""
        if self.dm != None:
            _dm = self.dm
            hwnd = _dm.FindWindowEx(0,"WTWindow","夜色")
            hwnd = _dm.FindWindowEx(hwnd,"CefBrowserWindow","")
            hwnd = _dm.FindWindowEx(hwnd,"Chrome_WidgetWin_0","")
            hwnd = _dm.FindWindowEx(hwnd,"Chrome_RenderWidgetHostHWND","")
            if hwnd == 0:
                return self.hwnd
            print("已找到程序：" + str(hwnd))
            self.setHwnd(hwnd)
        return self.hwnd
    
    def getConfigHwnd(self):
        """ 查找通用登录器的句柄
            如果传进来参数，说明不需要读配置文件
        """
        if self.hwnd != 0:
            return self.hwnd
        if self.dm != None:
            _dm = self.dm
            _path = self.path + '\\config.ini'
            hwnd = _dm.ReadIni('config','hwnd',_path)
            hwnd_str = _dm.EnumWindow(hwnd,'','Internet Explorer_Server',2)
            _list = hwnd_str.split(',')
            try:
                hwnd = int(_list[0])
            except:
                hwnd = 0
                print("报错：你好像没有绑定游戏窗口")
            print(_list)
            if hwnd == 0:
                return self.hwnd
            self.setHwnd(hwnd)
        return self.hwnd
    
    def bindWindow(self,_dm,_hwnd):
        """根据句柄绑定指定窗口"""
        if _dm == None or int(_hwnd) == 0:
            return False
        dm_ret = _dm.BindWindow(int(_hwnd),"gdi","windows","windows",0)
        if dm_ret == 1:
            print("已绑定窗口：" + str(_hwnd))
            return True
        elif dm_ret != 1:
            print("绑定窗口失败：" + str(_hwnd))
            return False
    
    def setShowError(self):
        """关闭大漠插件报错弹窗"""
        if self.dm != None:
            self.dm.SetShowErrorMsg(0)
            return True
        else:
            return False
    
    def setFont(self):
        """设置大漠字库"""
        if self.dm != None:
            _dm = self.dm
            _path = self.path + '\\Font\\'
            _dm.SetDict(0,_path + '字库.txt')
            _dm.SetDict(2,_path + '字库2.txt')
            _dm.SetDict(3,_path + '字库3.txt')
            _dm.SetDict(4,_path + '字库4.txt')
            _dm.SetDict(5,_path + '字库5.txt')
            _dm.SetDict(6,_path + '字库6.txt')
            _dm.UseDict(5)
            return True
        else:
            return False
    
    def readIni(self,section='0000_1',key='区域',filePath=''):
        """读取Ini配置文件"""
        if self.dm != None:
            return self.dm.ReadIni(section,key,filePath)
        else:
            return ''
    
    def writeIni(self,section='0000_1',key='区域',value='',filePath=''):
        """写入Ini配置文件"""
        if self.dm != None:
            isWri = self.dm.WriteIni(section,key,value,filePath)
            if isWri == 0:
                return False
            elif isWri == 1:
                return True
        else:
            return False
    
    def deleteIni(self,section='0000_1',filePath=''):
        """删除配置文件"""
        if self.dm != None:
            isDel = self.dm.DeleteIni(section,'',filePath)
            if isDel == 0:
                return False
            elif isDel == 1:
                return True
        else:
            return False
    
    def moveTo(self,x,y):
        """让鼠标移动到指定位置"""
        if self.dm != None:
            isMov = self.dm.MoveTo(x,y)
            if isMov == 0:
                return False
            elif isMov == 1:
                return True
        else:
            return False
    
    def leftClick(self):
        """鼠标左键点击"""
        if self.dm != None:
            isCli = self.dm.LeftClick()
            if isCli == 0:
                return False
            elif isCli == 1:
                return True
        else:
            return False
            
    def findPic(self,x,y,x2,y2,_bmp='01.bmp'):
        """在游戏中查找图片所在位置"""
        if self.dm != None:
            _dm = self.dm
            _dm_ret = _dm.FindPic(x,y,x2,y2,_bmp,"000000",0.9,0)
            return _dm_ret
        else:
            return None
    
    def ocr(self,x1,y1,x2,y2,color_format):
        """识别文字返回字符串"""
        if self.dm != None:
            _dm = self.dm
            return _dm.Ocr(x1,y1,x2,y2,color_format,1.0)
        else:
            return ''
    
    def findStrFast(self,x1,y1,x2,y2,_string,color_format):
        """查找字符串返回坐标元组"""
        if self.dm != None:
            _dm = self.dm
            return _dm.FindStrFast(x1,y1,x2,y2,_string,color_format,1.0)
        else:
            return None
        